package com.wn.ticket.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wn.ticket.common.PageBean;
import com.wn.ticket.common.Utils;
import com.wn.ticket.entity.EntranceTicket;
import com.wn.ticket.entity.Order;
import com.wn.ticket.exception.StockNotEnoughException;
import com.wn.ticket.mapper.EntranceTicketMapper;
import com.wn.ticket.mapper.OrderMapper;
import com.wn.ticket.service.OrderService;
import com.wn.ticket.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @创建人 NST
 * @创建时间 2022/8/29
 * @描述
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EntranceTicketMapper entranceTicketMapper;

    /**
     * 增加订单 事务控制
     * @param order
     */
    @Transactional
    @Override
    public void add(Order order) {
        int stock = entranceTicketMapper.getById(order.getEntranceTicket().getId()).getNumber();
        int initNumber = entranceTicketMapper.getById(order.getEntranceTicket().getId()).getInitNumber();
        if (stock < order.getNumber()) {//购买数量超过库存 抛出自定义异常
            throw new StockNotEnoughException("余票不足！");
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String time = dateTimeFormatter.format(LocalDateTime.now());
        String no = "WN" + time + (int) ((Math.random() * 8999) + 1000);//随机编码
        order.setOrderNumber(no);//存储订单号
        order.setState("待付款");//默认订单初始状态为待付款
        DateTimeFormatter dateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String buyTime = dateTime.format(LocalDateTime.now());
        order.setBuyTime(buyTime);//订单下单时间为当前时间
        order.setDeleted("N");//默认新订单为未删除
        order.setPaymentWay("-");//新订单默认未支付 支付方式设置为'-'
        order.setSeat(initNumber-stock+1);//本订单初始座位号为门票数量-当前库存+1
        //查询对应门票价格 乘以购买数量 存入订单
        BigDecimal price = entranceTicketMapper.getById(order.getEntranceTicket().getId()).getPrice();
        order.setTotalPrice(price.multiply(new BigDecimal(String.valueOf(order.getNumber()))));
        orderMapper.add(order);//增加订单到数据库
        EntranceTicket entranceTicket = new EntranceTicket();
        entranceTicket.setId(order.getEntranceTicket().getId());
        entranceTicket.setNumber(stock-order.getNumber());//当前库存减去购买数量
        entranceTicketMapper.update(entranceTicket);//修改数据库所购买的门票的库存
    }

    /**
     * 按条件查询订单
     * @param orderVo
     * @return
     */
    @Override
    public PageBean<Order> getByCondition(OrderVo orderVo) {
        Page<Order> page = PageHelper.startPage(orderVo.getCurrPage(), orderVo.getPageSize());
        List<Order> list = orderMapper.getByCondition(orderVo.getOrder());
        return  Utils.getPageBean(Order.class,page,list,orderVo.getCurrPage(),orderVo.getPageSize());
    }

    @Override
    public List<Order> getByTimeNotIncludeCancel(Order order) {
        return orderMapper.getByTimeNotIncludeCancel(order);
    }

    @Scheduled(fixedDelay = 60*1000)//一分钟检查一次订单表中状态为待付款的订单 与当前时间对比 超过十五分钟状态改为已取消
    public void checkOrder() throws ParseException {
        log.debug("定时执行checkOrder任务！");
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        DateTimeFormatter dateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String now = dateTime.format(LocalDateTime.now());
        List<Order> orders = orderMapper.checkOrder("待付款");
        for (Order o : orders) {
            long buyTime = simpleFormat.parse(o.getBuyTime()).getTime();
            long nowTime = simpleFormat.parse(now).getTime();
            int minutes = (int) ((nowTime - buyTime)/(1000 * 60));
            if(minutes>=15){
                o.setState("已取消");
                orderMapper.update(o);
            }
        }
    }

    /**
     * 通过订单id查询订单，获取状态
     * @param orderId
     * @return
     */
    @Override
    public Order getStates(int orderId) {
        Order order=orderMapper.getOrderById(orderId);
        return order;
    }

    /**
     * 修改订单 只修改状态
     * @param order
     */
    @Override
    public void update(Order order) {
        orderMapper.update(order);
    }

    /**
     * 根据订单id查订单信息
     * @param orderId
     * @return
     */
    @Override
    public Order getOrderById(int orderId) {
        return orderMapper.getOrderById(orderId);
    }

    /**
     * 历史订单
     * @param userId
     * @return
     */
    @Override
    public List<Order> getOrdersByUserId(int userId) {
        List<Order> orders = orderMapper.getOrdersByUserId(userId);
        return orders;
    }

    @Override
    public List<Order> getTicketByUserId(int userId) {
        List<Order> orders= orderMapper.getTicketByUserId(userId);
        return orders;
    }

    /**
     * 查询门票id
     *
     * @param id
     * @return
     */
    @Override
    public Order getByOrderId(int id) {
        return orderMapper.getByOrderId(id);
    }

}
